//
//  AYMFocusDoctorController.m
//  关注医生控制器
//
//  Created by xuNick on 16/5/6.
//  Copyright © 2016年 NN. All rights reserved.
//

#import "AYMFocusDoctorController.h"

#import "AYMFocusDoctorTableViewCell.h"

#import "AYMFocusDoctorModel.h"

#import "AYMFocusDoctorDetailController.h"

#define kDocArrayCodingFilePath [NSTemporaryDirectory() stringByAppendingPathComponent:@"docArray.data"]


static NSString *cellIdenfifier = @"focusCell";

@interface AYMFocusDoctorController ()<AYMFocusDoctorDetailControllerDelegate>

//医生列表
@property (nonatomic,strong)NSArray *doctorList;

@property (nonatomic,strong)AYMFocusDoctorModel *seletedModel;

@end

@implementation AYMFocusDoctorController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setupUI];
    //注册cell
    UINib *nib = [UINib nibWithNibName:@"FocusDoctorCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:cellIdenfifier];
}

#pragma mark - 私有方法

//存数据
-(void)saveDoclist{
    
    for (int i= 0; i< self.doctorList.count; i++) {
        
        AYMFocusDoctorModel *docModel = self.doctorList[i];
        [AYMSQLiteManager insertDoctorWithModel:docModel];
    }
}
//取数据
-(NSArray *)getLocalDocList{
    
    NSArray *docArr = [AYMSQLiteManager queryDoctor];
    self.doctorList = docArr;
    return docArr;
}
//更新
-(void)updateFocusWith:(NSInteger) docID andChange:(BOOL) isSeleted{
    //解档
    NSArray *fouceDocs = [self getLocalDocList];
    //修改数据
    if (!isSeleted) {
         //已经关注,不需要再关注
        for (AYMFocusDoctorModel *model in fouceDocs) {
            if (model.doctor_id.intValue == docID) {
               
                return;
            }
        }
        //加关注
        NSDictionary *para = @{@"user_id":@1000089,@"doctor_id":@300000315};
        [[AYMNetworkTool sharedManager]POST:@"http://iosapi.itcast.cn/addDoctor.json.php" parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //关注成功
            //重新下载数据
            [self loadDoctorList];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
        
    }else{
        //取消关注 http://iosapi.itcast.cn/deleteDoctor.json.php
        NSDictionary *para = @{@"user_id":@1000089,@"doctor_id":@300000315};
        [[AYMNetworkTool sharedManager]POST:@"http://iosapi.itcast.cn/deleteDoctor.json.php" parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //取消成功
            //重新下载数据
            [self loadDoctorList];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}

//初始化界面
-(void)setupUI{
    self.tableView.rowHeight = 85;
    //下载数据
    [self getDocList];
    
    self.title = @"选择医生";
    UIView *footerview = [[UIView alloc]init];
    self.tableView.tableFooterView = footerview;
    //设置下拉刷新
    MJRefreshNormalHeader *headerRefresh = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getDocList];
    }];
    
    self.tableView.mj_header = headerRefresh;
    
    //设置上啦刷新
    MJRefreshAutoNormalFooter *footerRefresh = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getDocList];
    
    }];
    self.tableView.mj_footer = footerRefresh;
}

//获取医生列表
-(void)getDocList{
    
    NSArray *temp = [self getLocalDocList];
    if (temp.count == 0) {
        [self loadDoctorList];
    }else{
        self.doctorList = temp;
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }

}


//下载医生列表
-(void)loadDoctorList{
        NSString *url = @"http://iosapi.itcast.cn/doctorList.json.php";
    
    NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",@"user_id":@(1000089),@"page_size":@(15),@"page":@(1)};
    [[AYMNetworkTool sharedManager]POST:url parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       //下载成功需要执行
        NSArray *tempArray = responseObject[@"data"];
        NSMutableArray *mutable = [NSMutableArray array];
        for (NSDictionary *dict in tempArray) {
            AYMFocusDoctorModel *model = [AYMFocusDoctorModel yy_modelWithDictionary:dict];
            [mutable addObject:model];
             [AYMSQLiteManager insertDoctorWithModel:model];
        }
        self.doctorList = mutable.copy;
        [self saveDoclist];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //下载失败需要执行
    }];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
     [SVProgressHUD dismiss];
}


#pragma mark - 数据源方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    Log(@"%ld",self.doctorList.count);
    return self.doctorList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AYMFocusDoctorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdenfifier];
    cell.model = self.doctorList[indexPath.row];
    //点击详情button推出控制器
    cell.PushDetailVC = ^{
        [self pushDetailVC];
    };
    return cell;
}

#pragma mark - 代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //弹出控制器
    AYMFocusDoctorDetailController *vc = [[AYMFocusDoctorDetailController alloc]init];
    vc.delegate = self;
    vc.model = self.doctorList[indexPath.row];
    self.seletedModel = vc.model;
    //给与model
    [SVProgressHUD dismiss];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)pushDetailVC{
    
    [SVProgressHUD showErrorWithStatus:@"医生关闭了咨询"];
}
 #pragma mark - 代理方法

-(void)focusDoctorDetailController:(BOOL)isCollecting{
    [self updateFocusWith:self.seletedModel.doctor_id.intValue andChange:isCollecting];
}

-(void)dealloc{
    [SVProgressHUD dismiss];
}

@end
